﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using DAL;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;


namespace PeisongWeb
{
    public partial class buyer_orderAdd : buyerPage
    {
        public int mode;
        public bool companyTypes = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("AB", 1))
                {
                    companyTypes = logic.company.listCompanyWeekWithByCompanyId(logic.customer.companyId);
                    CompanyEntity companyInfo = logic.company.getById(logic.customer.companyId);
                    lblCompanyName.Text = companyInfo.Company;

                    if (companyInfo.buyerType == "2")
                    {
                        hd_isTester.Value = "1";
                        //btn_Save.Enabled = false;
                    }
                    else
                    {
                        hd_isTester.Value = "0";
                    }

                    if (Request.QueryString["mode"] != null)
                    {
                        if (Library.Number.IsIntPositive(Request.QueryString["mode"]))
                        {
                            mode = Convert.ToInt32(Request.QueryString["mode"]);
                            this.hd_mode.Value = Request.QueryString["mode"].ToString();
                        }
                    }
                    getWebNews();
                    DropDownListBind();
                    companyGroupBind();
                    rptBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "buyer_index.html");
                    return;
                }
            }
        }

        private void companyGroupBind()
        {
            DataTable dt=CompanyGroup.listGroupByCompanyId(logic.customer.companyId);
            ddlMutilCompany.DataSource = dt;
            ddlMutilCompany.DataBind();

            if (dt.Rows.Count > 0)
            {
                ddlMutilCompany.SelectedIndex = ddlMutilCompany.Items.IndexOf(ddlMutilCompany.Items.FindByValue(logic.customer.companyId.ToString()));
            }
        }

        /*日期绑定，预定两个礼拜*/
        void DropDownListBind()
        {
            int dateCount = 14; //默认二周
            DateTime dt = DateTime.Now;
            if (companyTypes) //判断该企业用户是否为周价企业
                //dateCount = 0;
               dateCount = logic.buyerFixedPricePeriod.BuyerFixedPricePeriod_WithCountByDatetime(logic.customer.getCompanyId(),dt); //根据当前日期从数据得到符合该条件的配送日期的最后结束日期并返回当前日期与其的差 赋值 dataCount
            if (dateCount != 0)
            {
                for (int i = 0; i < dateCount; i++)
                {
                    DateTime currentDt = dt.AddDays(i + 1);
                    ddl_receiveDt.Items.Insert(i, new ListItem(currentDt.ToShortDateString() + " " + getDayOfWeek(Convert.ToInt32(currentDt.DayOfWeek)), dt.AddDays(i + 1).ToShortDateString()));
                }

                int companyId = logic.customer.getCompanyId();
                lbl_receiveTime.Text = hd_psTime.Value = logic.sysCode.getReceiveTime(logic.company.getById(companyId).ReceiveTime).Name;
                hd_companyType.Value = companyTypes == true ? "1" : "0";
            }
        }

        string getDayOfWeek(int week)
        {
            string[] srtWeek = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            return srtWeek[week];
        }
        private void rptBind()
        {
            if (!logic.company.listCompanyWeekWithByCompanyId(logic.customer.getCompanyId()))
            {
                DataTable dt = logic.recipeCategory.select(logic.customer.getCompanyId());
                rpt_list.DataSource = dt;
                rpt_list.DataBind();
            }
        }
        public string getRecipeList(int rcid)
        {
            DataTable dt = logic.recipe.select("rcid =" + rcid + "and [source]='2' and companyId=" + logic.customer.getCompanyId(), "recipeId", 100, 1).Tables[1];
            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in dt.Rows)
            {
                sb.Append("<li><span class='file2'>");
                sb.AppendFormat("<input type='checkbox' value='{0}' onclick='getProductByRecipe(this);' />", dr["recipeId"]);
                sb.AppendFormat("<span><a title='{0}'>{0}</a><img alt='' src='/app_common/images/select.gif' style='display:none' /></span>", dr["name"]);
                sb.Append("</span></li>");
            }
            return sb.ToString();
        }
        protected void lbtn_Submit_Click(object sender, EventArgs e)
        {

            try
            {
                List<DAL.OrderItemEntity> listPro = JsonConvert.DeserializeObject<List<DAL.OrderItemEntity>>(this.hd_loadval.Value);  //得到商品的细目
                if (listPro.Count > 0)
                {
                    int userid = logic.customer.userId;
                    int companyid = logic.customer.companyId;
                    OrderEntity od = new OrderEntity();
                    //od.Amount = Convert.ToDecimal(hd_amount.Value);
                    decimal totalAmount = 0m;
                    listPro.ForEach(item => totalAmount += item.Price * item.Quantity);
                    od.Amount = Math.Round(totalAmount, 2, MidpointRounding.AwayFromZero);//默认为MidpointRounding.ToEven(银行家舍入)算法，四舍六入五取偶
                    //if (!string.IsNullOrEmpty(ddlMutilCompany.SelectedValue))
                    //{
                    //    od.CompanyId = Convert.ToInt32(ddlMutilCompany.SelectedValue);
                    //}
                    //else
                    //{
                    //    od.CompanyId = companyid;
                    //}
                    od.CompanyId = companyid;
                    od.StandardAmount = od.Amount;
                    od.CustomerId = userid;
                    od.FireightFee = Convert.ToDecimal(0);  //运费
                    od.Note = txt_orderNote.Value;
                    od.OrderNo = ""; //传空值，存储过程自动得到订单编号
                    od.Source = "1";
                    od.Taxfee = Convert.ToDecimal(0); //发票
                    od.Status = "1";  //订单状态：“1”：已提交；“2”备货中；“3”已发货；“4”交易成功；“5”交易关闭；"6" 未生成
                    string hour = hd_psTime.Value;
                    string time = hour.Substring(hour.IndexOf("-") + 1, hour.Length - (hour.IndexOf("-") + 1));
                    od.ReceiveDt = Convert.ToDateTime(ddl_receiveDt.SelectedValue + " " + time);        //收货时间
                    od.TypeCount = listPro.Count;
                    TimeSpan dt = Convert.ToDateTime(ddl_receiveDt.SelectedValue)-DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
                    int day = dt.Days;
                    bool ctype = hd_companyType.Value == "1" ? true : false;
                    if (day > 1 && ctype == false) //配送日期大于一，并且企业类型不为一周报价企业
                    {
                        od.Status = "6";
                        int orderId = logic.order.insertDynamicOrder(od);
                        try
                        {
                            foreach (DAL.OrderItemEntity oi in listPro)
                            {
                                if (oi.SellerId == 0 && oi.SellerPrice == 0)
                                {
                                    log4net.ILog logger = log4net.LogManager.GetLogger("ApplicationFileAppender");
                                    logger.Info(string.Format("数据丢失:{0}", hd_SelPros.Value));
                                    PriceEntity pr = logic.price.getByProduct(oi.ProductId, oi.BusinessNature);
                                    oi.SellerId = pr.CompanyId;
                                    oi.SellerPrice = pr.SellerPrice;
                                }
                                oi.CustomerId = userid;
                                oi.InitQuantity = oi.Quantity;
                                oi.OrderId = orderId;
                                logic.orderItem.insertDynamicOrderItem(oi);
                            }
                        }
                        catch(Exception ex)
                        {
                            #region 日志跟踪
                            if (System.Configuration.ConfigurationManager.AppSettings["EnabledErrorReport"] == "1")
                            {
                                log4net.ILog logger = log4net.LogManager.GetLogger("ApplicationFileAppender");//读取log4net的配置文件
                                logger.Info(string.Format("错误详细信息：{0},商品信息：{1}", ex.StackTrace, hd_SelPros.Value));

                                ScriptManager.RegisterStartupScript(this, this.GetType(), "keyToS", "alert('订单数据失效，请联系客服!');", true);
                            }
                            #endregion 
                        }
                        hd_orderid.Value = orderId.ToString();
                        lbl_orderno.Text = "（临时订单号）" + orderId.ToString();
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "key", "orderSuccess();", true);
                    }
                    else
                    {
                        int orderid = logic.order.insert(od);
                        try
                        {
                            foreach (DAL.OrderItemEntity oi in listPro)
                            {
                                if (oi.SellerId == 0 && oi.SellerPrice == 0)
                                {
                                    log4net.ILog logger = log4net.LogManager.GetLogger("ApplicationFileAppender");//读取log4net的配置文件
                                    logger.Info(string.Format("数据丢失：{0}", hd_SelPros.Value));
                                    PriceEntity pr = logic.price.getByProduct(oi.ProductId, oi.BusinessNature);
                                    oi.SellerId = pr.CompanyId;
                                    oi.SellerPrice = pr.SellerPrice;
                                }
                                oi.CustomerId = userid;
                                oi.InitQuantity = oi.Quantity;
                                oi.OrderId = orderid;
                                logic.orderItem.insert(oi);
                            }
                        }
                        catch (Exception ex)
                        {
                            #region 日志跟踪
                            if (System.Configuration.ConfigurationManager.AppSettings["EnabledErrorReport"] == "1")
                            {
                                log4net.ILog logger = log4net.LogManager.GetLogger("ApplicationFileAppender");//读取log4net的配置文件
                                logger.Info(string.Format("错误详细信息：{0},商品信息：{1}", ex.StackTrace, hd_SelPros.Value));

                                ScriptManager.RegisterStartupScript(this, this.GetType(), "keyToS", "alert('订单数据失效，请联系客服!');", true);
                            }
                            #endregion
                        }

                        hd_orderid.Value = orderid.ToString();
                        lbl_orderno.Text = logic.order.getById(orderid).OrderNo;
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "key", "orderSuccess();", true);
                    }
                }
                else
                { }
            }
            catch
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "skey", "alert('订单数据失效，请联系客服!');", true);
                return;
            }

        }
        public void getWebNews()
        {
            DataTable dt = logic.webNews.select("isShow=1", "id desc", 100, 1).Tables[1];
            rpt_news.DataSource = dt;
            rpt_news.DataBind();
        }

     
    }
}
